package music

import (
	"fmt"
	url2 "net/url"
	"spider/sink"
	"strconv"
	"os"
	"spider/constants"
	"spider/encrypt"
	"strings"
	"net/http"
	"io/ioutil"
	"musicStruct"
	"encoding/json"
)

func getParams(SongId string,PageNo string) (content map[string]string,err error) {
	commentReqBody := musicStruct.CommentRequestBody{
		Rid: "R_SO_4_" + SongId,
		ThreadId: "R_SO_4_" + SongId,
		PageNo:    PageNo,
		Offset:    "0",
		OrderType:"1",
		Cursor:"-1",
		PageSize:     "20",
		CsrfToken: "",
	}
	jsonParams, err := json.Marshal(commentReqBody)

	content = make(map[string]string)
	randomBytes := encrypt.RandomStr(16)
	params, err := encrypt.AesEncrypt(string(jsonParams), constants.SrcretKey, constants.AseKey)
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	params, err = encrypt.AesEncrypt(params, string(randomBytes), constants.AseKey)
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	encSecKey := encrypt.RsaEncrypt(string(randomBytes), constants.PubKey, constants.Modulus)
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	content["params"] = string(params)
	content["encSecKey"] = string(encSecKey)
	return
}
func GetComment(SongId string)(){
	var PageNo = "1";
	var url string ="https://music.163.com/weapi/comment/resource/comments/get?csrf_token="//请求地址不变改变 只改变歌曲ID
	body,err := getParams(SongId,PageNo)
	if err != nil {
		return
	}
	var params string = body["params"]
	var encSecKey string = body["encSecKey"]
	postComment(url,params,encSecKey,SongId)

	//var b,_ = getComment(url,params,encSecKey)
	//fmt.Println(string(b))
	//main1(params,encSecKey)
}

func postComment(url string,params  string ,encSecKey string,SongId string){
	method := "POST"
	body1 := make(url2.Values)
	body1["params"] = []string{params}
	body1["encSecKey"] = []string{encSecKey}
	client := &http.Client {
	}
	req, err := http.NewRequest(method, url, strings.NewReader(body1.Encode()))

	//fmt.Println(strings.NewReader(body1.Encode()))
	if err != nil {
		fmt.Println(err)
		return
	}
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	//req.Header.Add("Cookie", "00OUgVZoyZNg6dnb0dVnP-zhSjWJh8AAAF4dDi8GA")

	res, err := client.Do(req)

	if err != nil {
		fmt.Println(err)
		return
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err)
		return
	}


	var json1 musicStruct.AutoGenerated
	json.Unmarshal([]byte(string(body)), &json1)
	//最新评论
	newComs := make([]musicStruct.MusicComments, 0, len(json1.Data.Comments ))

	for _, v := range json1.Data.Comments {
		str := strconv.FormatInt(v.Time,10)
		createtime := str[0 : len(str)-3]
		newComs = append(newComs, musicStruct.MusicComments{
			SongId,
			v.User.UserID,
			v.User.Nickname,
			v.User.AvatarURL,
			v.Content,
			v.CommentID,
			createtime,
		})
	}
	////保存评论
	saveComments(newComs)
	hotComs := make([]musicStruct.MusicComments, 0, len(json1.Data.HotComments ))
	//最火评论
	for _, v := range json1.Data.HotComments {
		str := strconv.FormatInt(v.Time,10)
		createtime := str[0 : len(str)-3]
		hotComs =append(hotComs,musicStruct.MusicComments{
			SongId,
			v.User.UserID,
			v.User.Nickname,
			v.User.AvatarURL,
			v.Content,
			v.CommentID,
			createtime,
		})
	}
	//保存评论
	saveComments(hotComs)
}

func saveComments(comments []musicStruct.MusicComments){
	mysqlSink, err := sink.NewMysqlSink()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer mysqlSink.Close()
	for _, comment := range comments {
		//fmt.Printf("打印结构体指针数组1：%v \n", comment)
		//判断数据库是否存在该评论
		_,err := mysqlSink.GetComment(comment)
		if err != nil {
			err := mysqlSink.InsertComment(comment)
			if err != nil {
				fmt.Println(err)
				break
			}
		}
	}
	defer mysqlSink.Close()
}
